#!/usr/bin/env python
import socket
import os,sys
import json
import argparse

class Protocol:
	def __init__(self,sockpath):
		self.__connect=self.__initconnect(sockpath)

	def __initconnect(self,sockpath):
		sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
		try:
			sock.connect(sockpath)
		except socket.error,e:
			print e
			sock.close()
			sys.exit(1)

		return sock

	def send(self,cmd,data):
		jsonob={"cmd":cmd,"data":data}
		try:
			self.__connect.send(json.dumps(jsonob))
		except socket.error,e:
			print e
			sys.exit(1)


	def recv(self):
		try:
			return json.loads(self.__connect.recv(1024))
		except socket.error,e:
			print e
			sys.exit(1)
			
class Client:
	def __init__(self,protocol):
		self.__protocol=protocol

	def list(self,**undefine):
		self.__protocol.send("list",None)
		data= self.__protocol.recv()

		if data["code"] == 200:
			tmp = data["data"]
				
			if tmp:
				dir_list=[x[0] for x in tmp]
				result = [(k+1,v.strip()) for k,v in enumerate(dir_list)]
				
				for i in result:
					print str(i[0]).ljust(len(str(result[-1][0]))+1)+"-".ljust(2)+i[1]
	
				sys.exit(0)

		else:
			sys.exit(1)

	def add(self,**data):
		path = data["dir"]
		if not os.path.exists(path):
			sys.exit(1)

		if path in ("..",".","/"):
			sys.exit(1)

		self.__protocol.send("add",path)
		data= self.__protocol.recv()

		if data["code"] == 200:
			sys.exit(0)

		else:
			sys.exit(1)

	def get(self,**data):
		self.__protocol.send("get",data["id"])
		data= self.__protocol.recv()

		if data["code"] == 200:
			print data["data"]
			sys.exit(0)

		else:
			sys.exit(1)


class MyFormat(argparse.HelpFormatter):
    def _format_actions_usage(self, actions, groups):
        return argparse.HelpFormatter._format_actions_usage(self, actions, groups).lower()

    def _format_action_invocation(self, action):
        return argparse.HelpFormatter._format_action_invocation(self, action).lower()

def execute_args():
	parser = argparse.ArgumentParser(description='dircli help',formatter_class=MyFormat)
	subparsers = parser.add_subparsers()

	parser.add_argument('-s', action="store",default="/tmp/dircached.sock",dest="sock",help="unix sock default:/tmp/dircached.sock")

	# add
	p = subparsers.add_parser('add', help='add dir',formatter_class=MyFormat)
	p.add_argument('dir', action="store",help="add dir")

	# list
	p = subparsers.add_parser('list', help='list cache',formatter_class=MyFormat)

	# get
	p = subparsers.add_parser('get', help='get by id',formatter_class=MyFormat)
	p.add_argument('id', action="store",type=int,help="dir id")
    
	return parser


def execute_command(args=sys.argv[1:]):
	a = execute_args().parse_args(args)
	c=Client(Protocol(a.sock))

	# call function
	commands = {
		'add': c.add,
		'list': c.list,
		'get':c.get
	}

	func = commands[args[0]]
	func(**a.__dict__)

if __name__ == '__main__':
	reload(sys)
	sys.setdefaultencoding("utf-8")
	execute_command()